package com.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.task.common.entity.sys.Permission;
import com.task.common.entity.sys.RolePermission;
import com.task.common.util.model.FieldUtil;
import com.task.common.util.string.StringUtils;
import com.task.mapper.PermissionMapper;
import com.task.mapper.RolePermissionMapper;
import com.task.service.IPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Huzz
 * @since 2021-10-11
 */
@Slf4j
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<Permission> getLoginUserPermissionByRoleId(Set<Integer> roleIds) {

        return permissionMapper.getLoginUserPermissionByRoleId(roleIds);
    }

    @Override
    public boolean permissionDistribute(Integer permissionId, Integer roleId) {

        RolePermission rolePermission = new RolePermission();
        rolePermission.setPermissionId(permissionId);
        rolePermission.setRoleId(roleId);
        FieldUtil.setCreatedAndUpdateField(rolePermission);
        return rolePermissionMapper.insert(rolePermission) > 0;
    }

    @Override
    public Page<Permission> findPermissionList(Integer pageNum, Integer pageSie, Permission model) {
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(model.getName())) {
            wrapper.eq(Permission::getName, model.getName());
        }
        if (!StringUtils.isEmpty(model.getDescription())) {
            wrapper.like(Permission::getDescription, model.getDescription());
        }
        return this.baseMapper.selectPage(new Page<>(pageNum, pageSie), wrapper);
    }

    @Override
    public boolean addPermission(Permission permission) {
        FieldUtil.setCreatedAndUpdateField(permission);
        return this.baseMapper.insert(permission) > 0;
    }

    @Override
    public List<Permission> selectListByPath(String requestUrl) {

        return permissionMapper.selectListByPath(requestUrl);
    }
}
